<template>
  <div>
    <form @submit.prevent="modifyStage()">
      <div class="mb-3 row">
        <label class="col-sm-2 col-form-label">阶段名称</label>
        <div class="col-sm-10">
          <input
            type="text"
            class="form-control"
            v-model="stage.stname"
            required="required"
          />
        </div>
      </div>
      <div class="mb-3 row">
        <label for="inputPassword" class="col-sm-2 col-form-label"
          >所属学科</label
        >
        <div class="col-sm-10">
          <el-select v-model="stage.subject.id" placeholder="请选择">
            <el-option
              v-for="item in subjects"
              :key="item.id"
              :label="item.sname"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </div>
      </div>
      <button type="submit" class="btn btn-secondary">提交</button>
      <router-link to="/stage/list" class="btn btn-secondary">返回</router-link>
    </form>
  </div>
</template>

<script>
export default {
  name: "StageModify",
  data() {
    return {
      stage: {
        id: 0,
        stname: "",
        subject: { id: "", sname: "" },
      },
      initstname: "",
      subjects: [],
    };
  },
  props: {
    id: {
      type: String,
      default: null,
    },
  },
  mounted() {
    this.$parent.stageTitle = "阶段修改";
    this.getStage();
    this.getSubject();
  },
  methods: {
    getStage() {
      this.axiosJSON.get("/stage/getOne?id=" + this.id).then((result) => {
        this.stage = result.data.data;
        this.initData();
      });
    },
    modifyStage() {
      //判断初始值与当前值是否相同且id值类型是否是字符串类型，即页面的值是否被修改过
      if(this.initstname == this.stage.stname && typeof this.stage.subject.id == "string")
        this.$message({type:"warning",message:"请修改值在提交"})
      else
        //如果值被修改，发起update请求
        this.axiosJSON.post("/stage/update", this.stage).then((result) => {
          if (result.data.code == 0) {
            this.$message({
              type: "success",
              message: result.data.msg,
            });
            this.$router.push("/stage/list");
          } else {
            this.$message.error(result.data.msg);
          }
        });
    },
    getSubject() {
      this.axiosJSON.post("/subject/getAllWithoutPage").then((result) => {
        this.subjects = result.data.data;
      });
    },
    initData(){
        //设置初始值，以比对值是否被修改过
        this.initstname = this.stage.stname
        //将名字值赋给id，以实现页面加载后下拉框是名字而不是id的需求
        this.stage.subject.id = this.stage.subject.sname; 
    }
  },
};
</script>

<style>
</style>